<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品" prop="productId">
        <id-selector
          v-model="queryParams.productId"
          placeholder="请选择商品"
          dialog-title="选择商品"
          :api-function="listProduct"
          :get-api-function="getProduct"
          id-field="productId"
          name-field="productName"
          id-label="商品ID"
          name-label="商品名称"
          search-label="商品名称"
          search-placeholder="请输入商品名称"
          :extra-columns="[{prop: 'productCode', label: '商品编码'}, {prop: 'price', label: '价格'}]"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userId">
        <id-selector
          v-model="queryParams.userId"
          placeholder="请选择用户"
          dialog-title="选择用户"
          :api-function="listUser"
          :get-api-function="getUser"
          id-field="userId"
          name-field="userName"
          id-label="用户ID"
          name-label="用户名称"
          search-label="用户名称"
          search-placeholder="请输入用户名称"
          :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分" prop="star">
        <el-input
          v-model="queryParams.star"
          placeholder="请输入评分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="showStatus">
        <el-select v-model="queryParams.showStatus" placeholder="请选择显示状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_show_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 新增、修改、删除按钮已删除 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:comment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品" align="center" prop="productName" width="150" show-overflow-tooltip />
      <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" align="center" prop="userName" />
      <el-table-column label="评分" align="center" prop="star" />
      <el-table-column label="评价内容" align="center" prop="content" width="200" show-overflow-tooltip />
      <el-table-column label="评价图片" align="center" prop="images" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商家回复" align="center" prop="replyContent" />
      <el-table-column label="回复时间" align="center" prop="replyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.replyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示状态" align="center" prop="showStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_show_status" :value="scope.row.showStatus"/>
        </template>
      </el-table-column>
      <!-- 操作列已隐藏 -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fun:comment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:comment:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品评价对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品" prop="productId">
          <id-selector
            v-model="form.productId"
            placeholder="请选择商品"
            dialog-title="选择商品"
            :api-function="listProduct"
            :get-api-function="getProduct"
            id-field="productId"
            name-field="productName"
            id-label="商品ID"
            name-label="商品名称"
            search-label="商品名称"
            search-placeholder="请输入商品名称"
            :extra-columns="[{prop: 'productCode', label: '商品编码'}, {prop: 'price', label: '价格'}]"
          />
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <id-selector
            v-model="form.userId"
            placeholder="请选择用户"
            dialog-title="选择用户"
            :api-function="listUser"
            :get-api-function="getUser"
            id-field="userId"
            name-field="userName"
            id-label="用户ID"
            name-label="用户名称"
            search-label="用户名称"
            search-placeholder="请输入用户名称"
            :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
          />
        </el-form-item>
        <el-form-item label="订单" prop="orderId">
          <id-selector
            v-model="form.orderId"
            placeholder="请选择订单"
            dialog-title="选择订单"
            :api-function="listOrder"
            :get-api-function="getOrder"
            id-field="orderId"
            name-field="orderNo"
            id-label="订单ID"
            name-label="订单号"
            search-label="订单号"
            search-placeholder="请输入订单号"
            :extra-columns="[{prop: 'totalAmount', label: '订单金额'}, {prop: 'orderStatus', label: '订单状态'}]"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="评分" prop="star">
          <el-input v-model="form.star" placeholder="请输入评分" :disabled="true" />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入评价内容" :disabled="true" />
        </el-form-item>
        <el-form-item label="评价图片" prop="pics">
          <image-upload v-model="form.pics" :limit="5" :disabled="true" />
        </el-form-item>
        <el-form-item label="显示状态" prop="showStatus">
          <el-radio-group v-model="form.showStatus">
            <el-radio
              v-for="dict in dict.type.ec_show_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listComment, getComment, delComment, addComment, updateComment } from "@/api/fun/comment"
import { getDept } from "@/api/system/dept"
import { listProduct, getProduct } from "@/api/fun/product"
import { listUser, getUser } from "@/api/system/user"
import { listOrder, getOrder } from "@/api/fun/order"
import IdSelector from "@/components/IdSelector"
import ImageUpload from "@/components/ImageUpload"
import ImagePreview from "@/components/ImagePreview"

export default {
  name: "Comment",
  components: {
    IdSelector,
    ImageUpload,
    ImagePreview
  },
  dicts: ['ec_show_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品评价表格数据
      commentList: [],
      // 部门名称缓存
      deptNameCache: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        star: [
          { required: true, message: "评分不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "评价内容不能为空", trigger: "blur" }
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        orderId: null,
        userId: null,
        userName: null,
        star: null,
        content: null,
        images: null,
        replyContent: null,
        replyTime: null,
        showStatus: null,
      },

    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 监听表单提交事件
    this.$eventBus.$on('refreshCommentList', () => {
      this.getList()
    })
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$eventBus.$off('refreshCommentList')
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      if (!deptId) return '-'
      if (this.deptNameCache[deptId]) {
        return this.deptNameCache[deptId]
      }
      // 异步获取部门名称
      getDept(deptId).then(response => {
        this.$set(this.deptNameCache, deptId, response.data.deptName)
        // 强制更新视图
        this.$forceUpdate()
      }).catch(() => {
        this.$set(this.deptNameCache, deptId, '未知组织')
        this.$forceUpdate()
      })
      return deptId // 先显示ID，异步加载完成后显示名称
    },
    /** 查询商品评价列表 */
    getList() {
      this.loading = true
      listComment(this.queryParams).then(response => {
        this.commentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.commentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        commentId: null,
        productId: null,
        orderId: null,
        userId: null,
        userName: null,
        star: null,
        content: null,
        pics: null,
        replyContent: null,
        replyTime: null,
        showStatus: "1",
        createTime: null
      }
      this.resetForm("form")
    },
    /** 新增按钮操作 */
    handleAdd() {
      const obj = { path: "/fun/comment/form", query: { pageType: "add" } };
      this.$tab.openPage("新增商品评价", obj.path, obj.query);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const commentId = row.commentId || this.ids;
      const obj = { path: "/fun/comment/form", query: { pageType: "edit", commentId: commentId } };
      this.$tab.openPage("修改商品评价", obj.path, obj.query);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.commentId != null) {
            updateComment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addComment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const commentIds = row.commentId || this.ids
      this.$modal.confirm('是否确认删除商品评价编号为"' + commentIds + '"的数据项？').then(function() {
        return delComment(commentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/comment/export', {
        ...this.queryParams
      }, `comment_${new Date().getTime()}.xlsx`)
    },
    /** 获取第一张图片 */
    getFirstImage(images) {
      if (!images) return null
      const imageList = images.split(',')
      return imageList.length > 0 ? imageList[0].trim() : null
    },
    /** 图片加载错误处理 */
    handleImageError() {
      // 图片加载失败时的处理逻辑
    },
    // API方法
    listProduct,
    getProduct,
    listUser,
    getUser,
    listOrder,
    getOrder
  }
}
</script>
